{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\Administrator\\Anaconda3\\lib\\requests\\__init__.py:80: RequestsDependencyWarning: urllib3 (1.25.11) or chardet (3.0.4) doesn't match a supported version!\n",
      "  RequestsDependencyWarning)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "matchzoo version 1.0.2\n",
      "`ranking_task` initialized with metrics [normalized_discounted_cumulative_gain@3(0.0), normalized_discounted_cumulative_gain@5(0.0), mean_average_precision(0.0)]\n",
      "data loading ...\n",
      "data loaded as `train_pack_raw` `dev_pack_raw` `test_pack_raw`\n",
      "停用表配置成功\n"
     ]
    }
   ],
   "source": [
    "%run init.ipynb"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# ranking_task = mz.tasks.Ranking(losses=mz.losses.RankCrossEntropyLoss(num_neg=4))\n",
    "# ranking_task.metrics = [\n",
    "#     mz.metrics.NormalizedDiscountedCumulativeGain(k=3),\n",
    "#     mz.metrics.NormalizedDiscountedCumulativeGain(k=5),\n",
    "#     mz.metrics.MeanAveragePrecision()\n",
    "# ]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Processing text_left with chain_transform of ChineseRemoveBlack => ChineseSimplified => ChineseEmotion => IsChinese => ChineseStopRemoval => ChineseTokenizeDemo => Tokenize => Lowercase => PuncRemoval:   0%| | 0/94 [00:00<?, ?it/s]Building prefix dict from the default dictionary ...\n",
      "Loading model from cache C:\\Users\\ADMINI~1\\AppData\\Local\\Temp\\jieba.cache\n",
      "Loading model cost 1.160 seconds.\n",
      "Prefix dict has been built succesfully.\n",
      "Processing text_left with chain_transform of ChineseRemoveBlack => ChineseSimplified => ChineseEmotion => IsChinese => ChineseStopRemoval => ChineseTokenizeDemo => Tokenize => Lowercase => PuncRemoval: 100%|█| 94/94 [00:01<00:00, 56.08it/s]\n",
      "Processing text_right with chain_transform of ChineseRemoveBlack => ChineseSimplified => ChineseEmotion => IsChinese => ChineseStopRemoval => ChineseTokenizeDemo => Tokenize => Lowercase => PuncRemoval: 100%|█| 99/99 [00:00<00:00, 199.30it/s]\n",
      "Processing text_right with append: 100%|████████████████████████████████████████████| 99/99 [00:00<00:00, 19798.60it/s]\n",
      "Building FrequencyFilter from a datapack.: 100%|████████████████████████████████████| 99/99 [00:00<00:00, 19813.72it/s]\n",
      "Processing text_right with transform: 100%|█████████████████████████████████████████| 99/99 [00:00<00:00, 49450.53it/s]\n",
      "Processing text_left with extend: 100%|█████████████████████████████████████████████| 94/94 [00:00<00:00, 47048.28it/s]\n",
      "Processing text_right with extend: 100%|████████████████████████████████████████████| 99/99 [00:00<00:00, 33026.02it/s]\n",
      "Building Vocabulary from a datapack.: 100%|██████████████████████████████████████| 950/950 [00:00<00:00, 316262.31it/s]\n",
      "Processing text_left with transform: 100%|██████████████████████████████████████████| 94/94 [00:00<00:00, 46958.62it/s]\n",
      "Processing text_right with transform: 100%|█████████████████████████████████████████| 99/99 [00:00<00:00, 19804.27it/s]\n",
      "Processing text_left with extend: 100%|█████████████████████████████████████████████| 94/94 [00:00<00:00, 93962.01it/s]\n",
      "Processing text_right with extend: 100%|████████████████████████████████████████████| 99/99 [00:00<00:00, 50010.37it/s]\n",
      "Building Vocabulary from a datapack.: 100%|██████████████████████████████████████| 950/950 [00:00<00:00, 158395.17it/s]\n",
      "Processing text_left with chain_transform of ChineseRemoveBlack => ChineseSimplified => ChineseEmotion => IsChinese => ChineseStopRemoval => ChineseTokenizeDemo => Tokenize => Lowercase => PuncRemoval: 100%|█| 94/94 [00:00<00:00, 189.63it/s]\n",
      "Processing text_right with chain_transform of ChineseRemoveBlack => ChineseSimplified => ChineseEmotion => IsChinese => ChineseStopRemoval => ChineseTokenizeDemo => Tokenize => Lowercase => PuncRemoval: 100%|█| 99/99 [00:00<00:00, 108.97it/s]\n",
      "Processing text_right with transform: 100%|█████████████████████████████████████████| 99/99 [00:00<00:00, 24769.51it/s]\n",
      "Processing text_left with transform: 100%|██████████████████████████████████████████| 94/94 [00:00<00:00, 18798.67it/s]\n",
      "Processing text_right with transform: 100%|█████████████████████████████████████████| 99/99 [00:00<00:00, 98936.41it/s]\n",
      "Processing length_left with len: 100%|██████████████████████████████████████████████| 94/94 [00:00<00:00, 47279.60it/s]\n",
      "Processing length_right with len: 100%|█████████████████████████████████████████████| 99/99 [00:00<00:00, 99768.40it/s]\n",
      "Processing text_left with chain_transform of ChineseRemoveBlack => ChineseSimplified => ChineseEmotion => IsChinese => ChineseStopRemoval => ChineseTokenizeDemo => Tokenize => Lowercase => PuncRemoval: 100%|█| 48/48 [00:00<00:00, 147.78it/s]\n",
      "Processing text_right with chain_transform of ChineseRemoveBlack => ChineseSimplified => ChineseEmotion => IsChinese => ChineseStopRemoval => ChineseTokenizeDemo => Tokenize => Lowercase => PuncRemoval: 100%|█| 50/50 [00:00<00:00, 185.99it/s]\n",
      "Processing text_right with transform: 100%|█████████████████████████████████████████| 50/50 [00:00<00:00, 25001.81it/s]\n",
      "Processing text_left with transform: 100%|██████████████████████████████████████████| 48/48 [00:00<00:00, 16031.74it/s]\n",
      "Processing text_right with transform: 100%|█████████████████████████████████████████| 50/50 [00:00<00:00, 25013.74it/s]\n",
      "Processing length_left with len: 100%|██████████████████████████████████████████████| 48/48 [00:00<00:00, 12008.03it/s]\n",
      "Processing length_right with len: 100%|█████████████████████████████████████████████| 50/50 [00:00<00:00, 25097.56it/s]\n",
      "Processing text_left with chain_transform of ChineseRemoveBlack => ChineseSimplified => ChineseEmotion => IsChinese => ChineseStopRemoval => ChineseTokenizeDemo => Tokenize => Lowercase => PuncRemoval: 100%|█| 28/28 [00:00<00:00, 151.42it/s]\n",
      "Processing text_right with chain_transform of ChineseRemoveBlack => ChineseSimplified => ChineseEmotion => IsChinese => ChineseStopRemoval => ChineseTokenizeDemo => Tokenize => Lowercase => PuncRemoval: 100%|█| 30/30 [00:00<00:00, 147.87it/s]\n",
      "Processing text_right with transform: 100%|██████████████████████████████████████████| 30/30 [00:00<00:00, 5997.86it/s]\n",
      "Processing text_left with transform: 100%|███████████████████████████████████████████| 28/28 [00:00<00:00, 4669.42it/s]\n",
      "Processing text_right with transform: 100%|█████████████████████████████████████████| 30/30 [00:00<00:00, 29973.59it/s]\n",
      "Processing length_left with len: 100%|███████████████████████████████████████████████| 28/28 [00:00<00:00, 9328.82it/s]\n",
      "Processing length_right with len: 100%|█████████████████████████████████████████████| 30/30 [00:00<00:00, 15067.55it/s]\n"
     ]
    }
   ],
   "source": [
    "preprocessor = mz.models.DSSM.get_default_preprocessor(ngram_size=3)\n",
    "train_pack_processed = preprocessor.fit_transform(train_pack_raw)\n",
    "dev_pack_processed = preprocessor.transform(dev_pack_raw)\n",
    "test_pack_processed = preprocessor.transform(test_pack_raw)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'embedding_input_dim': 344,\n",
       " 'filter_unit': <mzcn.preprocessors.units.frequency_filter.FrequencyFilter at 0x24003754518>,\n",
       " 'ngram_process_unit': <mzcn.preprocessors.units.ngram_letter.NgramLetter at 0x240077e93c8>,\n",
       " 'ngram_vocab_size': 344,\n",
       " 'ngram_vocab_unit': <mzcn.preprocessors.units.vocabulary.Vocabulary at 0x2400787b6d8>,\n",
       " 'vocab_size': 344,\n",
       " 'vocab_unit': <mzcn.preprocessors.units.vocabulary.Vocabulary at 0x24003754630>}"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "preprocessor.context"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "triletter_callback = mz.dataloader.callbacks.Ngram(\n",
    "    preprocessor, mode='aggregate')\n",
    "\n",
    "trainset = mz.dataloader.Dataset(\n",
    "    data_pack=train_pack_processed,\n",
    "    mode='pair',\n",
    "#     num_dup=1,\n",
    "#     num_neg=4,\n",
    "    callbacks=[triletter_callback]\n",
    ")\n",
    "devset = mz.dataloader.Dataset(\n",
    "    data_pack=dev_pack_processed,\n",
    "    callbacks=[triletter_callback]\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "padding_callback = mz.models.DSSM.get_default_padding_callback()\n",
    "\n",
    "trainloader = mz.dataloader.DataLoader(\n",
    "    dataset=trainset,\n",
    "#     batch_size=32,\n",
    "    stage='train',\n",
    "#     resample=True,\n",
    "    callback=padding_callback\n",
    ")\n",
    "devloader = mz.dataloader.DataLoader(\n",
    "    dataset=devset,\n",
    "#     batch_size=32,\n",
    "    stage='dev',\n",
    "    callback=padding_callback\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "DSSM(\n",
      "  (mlp_left): Sequential(\n",
      "    (0): Sequential(\n",
      "      (0): Linear(in_features=344, out_features=300, bias=True)\n",
      "      (1): ReLU()\n",
      "    )\n",
      "    (1): Sequential(\n",
      "      (0): Linear(in_features=300, out_features=300, bias=True)\n",
      "      (1): ReLU()\n",
      "    )\n",
      "    (2): Sequential(\n",
      "      (0): Linear(in_features=300, out_features=300, bias=True)\n",
      "      (1): ReLU()\n",
      "    )\n",
      "    (3): Sequential(\n",
      "      (0): Linear(in_features=300, out_features=128, bias=True)\n",
      "      (1): ReLU()\n",
      "    )\n",
      "  )\n",
      "  (mlp_right): Sequential(\n",
      "    (0): Sequential(\n",
      "      (0): Linear(in_features=344, out_features=300, bias=True)\n",
      "      (1): ReLU()\n",
      "    )\n",
      "    (1): Sequential(\n",
      "      (0): Linear(in_features=300, out_features=300, bias=True)\n",
      "      (1): ReLU()\n",
      "    )\n",
      "    (2): Sequential(\n",
      "      (0): Linear(in_features=300, out_features=300, bias=True)\n",
      "      (1): ReLU()\n",
      "    )\n",
      "    (3): Sequential(\n",
      "      (0): Linear(in_features=300, out_features=128, bias=True)\n",
      "      (1): ReLU()\n",
      "    )\n",
      "  )\n",
      "  (out): Linear(in_features=1, out_features=1, bias=True)\n",
      ") 645258\n"
     ]
    }
   ],
   "source": [
    "model = mz.models.DSSM()\n",
    "\n",
    "model.params['task'] = ranking_task\n",
    "model.params['vocab_size'] = preprocessor.context['ngram_vocab_size']\n",
    "model.params['mlp_num_layers'] = 3\n",
    "model.params['mlp_num_units'] = 300\n",
    "model.params['mlp_num_fan_out'] = 128\n",
    "model.params['mlp_activation_func'] = 'relu'\n",
    "\n",
    "model.build()\n",
    "\n",
    "print(model, sum(p.numel() for p in model.parameters() if p.requires_grad))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "optimizer = torch.optim.Adam(model.parameters())\n",
    "\n",
    "trainer = mz.trainers.Trainer(\n",
    "    model=model,\n",
    "    optimizer=optimizer,\n",
    "    trainloader=trainloader,\n",
    "    validloader=devloader,\n",
    "    validate_interval=None,\n",
    "    epochs=10\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "05ac814902704a4caa380297f6ef6da1",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-1 Loss-1.002]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.2121 - normalized_discounted_cumulative_gain@5(0.0): 0.2121 - mean_average_precision(0.0): 0.2121\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "70a47b9972204974bcfa5044bfaaf1bf",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-2 Loss-0.955]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.2121 - normalized_discounted_cumulative_gain@5(0.0): 0.2121 - mean_average_precision(0.0): 0.2121\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "5030e66442b2401eb17b1f1623a42eb5",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-3 Loss-0.897]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.2121 - normalized_discounted_cumulative_gain@5(0.0): 0.2121 - mean_average_precision(0.0): 0.2121\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "46d03fe8033e48bc8cb0d5496efa1d04",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-4 Loss-0.818]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.2009 - normalized_discounted_cumulative_gain@5(0.0): 0.2009 - mean_average_precision(0.0): 0.197\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "a85ee0defe1d4ea5b60a2f82ef7af53b",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-5 Loss-0.747]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.2009 - normalized_discounted_cumulative_gain@5(0.0): 0.2009 - mean_average_precision(0.0): 0.197\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "c635e07f30854f9cad0bc978124c3c1e",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-6 Loss-0.713]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.2009 - normalized_discounted_cumulative_gain@5(0.0): 0.2009 - mean_average_precision(0.0): 0.197\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "eb46192e105643d48422b0e767cdc90c",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-7 Loss-0.696]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.2009 - normalized_discounted_cumulative_gain@5(0.0): 0.2009 - mean_average_precision(0.0): 0.197\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "11c613b57d9d4741bbf52761a18ccdde",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-8 Loss-0.691]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.2009 - normalized_discounted_cumulative_gain@5(0.0): 0.2009 - mean_average_precision(0.0): 0.197\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "1dff220fbded468fa3dbd4bbd154dc79",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-9 Loss-0.689]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.2009 - normalized_discounted_cumulative_gain@5(0.0): 0.2009 - mean_average_precision(0.0): 0.197\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "10eed6c7f5ce467185c0cd6d5f6d1723",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-10 Loss-0.688]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.2009 - normalized_discounted_cumulative_gain@5(0.0): 0.2009 - mean_average_precision(0.0): 0.197\n",
      "\n",
      "Cost time: 4.221258878707886s\n"
     ]
    }
   ],
   "source": [
    "trainer.run()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "3178"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import gc\n",
    "gc.collect()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
